from django.core.context_processors import csrf
from django.http import HttpResponse
from django.core.servers.basehttp import FileWrapper
from django.shortcuts import render_to_response, get_object_or_404
from django.core.paginator import Paginator, InvalidPage, EmptyPage

from fontrender.converter.models import Category, Font
from fontrender.settings import LANGUAGES
from fontrender.converter.font_renderer import FontRenderer
from fontrender.converter.font_pygtk import PyGTKRenderer
from forms import ConverterForm

#import cairo
#import pango
#import pangocairo

import StringIO

def converter(request, slug_category='', slug_font=''):
    categories = Category.objects.all().order_by("-rating")
    if slug_category == '':
        return render_to_response('mainpage.html', {'categories': categories,'LANGUAGES':LANGUAGES})

    cr = get_object_or_404(Category, slug=slug_category)

    if slug_font != '':
        font = get_object_or_404(Font, slug=slug_font)
        if request.method == 'POST':
            form = ConverterForm(request.POST)
            if form.is_valid():
                cd = form.cleaned_data
                font.rating+=1
                cr.rating+=1
                font.save()
                cr.save()

                rendered_img = FontRenderer(font,cd)

                response = HttpResponse(content_type='image/png')
                response['Content-Disposition'] = 'attachment; filename=rendered_image.png'
                rendered_img.image().save(response, format='PNG')
                return response
        else:
            form = ConverterForm(
                    initial={'message': 'Test', 'letter_spacing': 0, 'leading': 'auto',
                             'vertical_scale':100,'horizontal_scale':100}
                    )
        return render_to_response('render_form.html',
                {'form': form, 'categories': categories, 
                    'cur_category':cr,'cur_font': font,'LANGUAGES':LANGUAGES})

    fonts_list_full = Font.objects.filter(category=cr).order_by("-rating")
    paginator = Paginator(fonts_list_full, 10)

    try:
        page = int(request.GET.get('page', '1'))
    except ValueError:
        page = 1

    try:
        fonts_list = paginator.page(page)
    except (EmptyPage, InvalidPage):
        fonts_list = paginator.page(paginator.num_pages)

    return render_to_response('font_choose.html',
            {'categories': categories, 'fonts': fonts_list,
                'cur_category':cr,'LANGUAGES':LANGUAGES})
